/**
 * User: coder.sdp@gmail.com
 * Date: 2023/9/8
 * Time: 14:18
 */

package zconf

import (
	"github.com/spf13/viper"
	"go_server/zinx/zlog"
	"os"
)

const (
	// EnvConfigFilePathKey (Set configuration file path export ZINX_CONFIG_FILE_PATH = xxxxxxzinx.json)
	// (设置配置文件路径 export ZINX_CONFIG_FILE_PATH = xxx/xxx/zinx.json)
	EnvConfigFilePathKey     = "go_server/zinx_CONFIG_FILE_PATH"
	envDefaultConfigFilePath = "/conf/"
	ConfigFileName           = "zinx"
)

func CreateConfig(configPath string) *viper.Viper {
	configFilePath := os.Getenv(EnvConfigFilePathKey)
	if configFilePath == "" {
		//pwd, err := os.Getwd()
		//if err != nil {
		//	panic(err)
		//}
		configFilePath = configPath
	}
	//var err error
	//configFilePath, err = filepath.Abs(configFilePath)
	//if err != nil {
	//	panic(err)
	//}

	config := viper.New()
	config.AddConfigPath(configFilePath)
	config.SetConfigName(ConfigFileName)
	config.SetConfigType("json")

	configFile := configFilePath + ConfigFileName + ".json"

	if err := config.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			zlog.Panicf("找不到配置文件: %s", configFile)
		} else {
			zlog.Panicf("解析配置文件 %s 出错: %v", configFile, err)
		}
	}
	return config
}
